// server/api/user/edit-history.get.ts
import { defineEventHandler, getQuery, getHeader } from 'h3'
import { verifyToken } from '../../utils/auth'

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({
        statusCode: 401,
        statusMessage: '未提供认证令牌'
      })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌无效或已过期'
      })
    }

    const userId = decoded.userId
    const query = getQuery(event)
    const page = parseInt(query.page as string) || 1
    const limit = parseInt(query.limit as string) || 10
    const skip = (page - 1) * limit

    // 查询编辑历史
    const [editHistory, totalCount] = await Promise.all([
      prisma.userEditHistory.findMany({
        where: { userId },
        skip,
        take: limit,
        orderBy: { editedAt: 'desc' },
        include: {
          user: {
            select: {
              username: true,
              email: true
            }
          }
        }
      }),
      prisma.userEditHistory.count({
        where: { userId }
      })
    ])

    const totalPages = Math.ceil(totalCount / limit)

    return {
      code: 200,
      message: '获取成功',
      data: {
        editHistory,
        pagination: {
          currentPage: page,
          pageSize: limit,
          totalCount,
          totalPages,
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    }
    
  } catch (error: any) {
    console.error('获取编辑历史错误:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '获取失败'
    })
  }
})